package com.lyn.pluginbazaar.service;

import com.lyn.pluginbazaar.api.FileAdapter;
import com.lyn.pluginbazaar.dao.plugin.Plugin;
import com.lyn.pluginbazaar.dao.plugin.PluginDao;
import com.lyn.pluginbazaar.entity.Result;
import com.lyn.pluginbazaar.utils.FileUtil;
import com.lyn.pluginbazaar.utils.ThreadPool;
import com.lyn.pluginbazaar.utils.UUidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;

@Service
public class FileService implements FileAdapter {

    @Autowired
    private PluginDao pluginDao;


    @Override
    public Result uploadPlugin(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        String filename = UUidUtil.getUid().concat(Objects.requireNonNull(file.getResource().getFilename()));
        checkUselessFile();
        try {
            if (!filename.endsWith(".apk") & !filename.endsWith(".jpg") & !filename.endsWith(".png")) {
                return Result.FAIL("请上传apk/jpg/png文件!");
            }
            FileUtil.saveFile(file.getInputStream(), filename);
            return Result.SUCCESS("上传文件成功!", filename);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.FAIL("上传文件失败!");
    }


    @Override
    public Result delete(String fileName) {
        if (FileUtil.delete(fileName)) {
            return Result.SUCCESS("删除成功!");
        }
        return Result.FAIL("删除失败!");
    }

    @Override
    public void download(String fileName, HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        FileUtil.fileToOutputStream(fileName, response);
    }

    @Override
    public void getImage(String fileName, HttpServletResponse response) {
        FileUtil.fileToOutputStream(fileName, response);
    }


    public void checkUselessFile() {
        ThreadPool.get().execute(new Runnable() {
            @Override
            public void run() {
                File file = new File(FileUtil.PLUGIN_FILE_PATH);
                if (file.exists() && file.isDirectory()) {
                    File[] files = file.listFiles();
                    for (File f : files) {
                        String name = f.getName();
                        Plugin plugin = pluginDao.findByPluginFileName(name);
                        if (plugin == null) {
                            f.delete();
                            System.out.println("删除:" + name);
                        }
                    }
                }
            }
        });
    }

}
